package com.wang.controller;

import cn.hutool.core.util.ObjectUtil;
import com.wang.constant.ErrorCode;
import com.wang.exception.BusinessException;
import com.wang.param.user.UserUpdateRequest;
import com.wang.reponse.UserDetailVo;
import com.wang.reponse.UserVo;
import com.wang.result.BaseResponse;
import com.wang.result.ResultUtils;
import com.wang.user.model.User;
import com.wang.user.service.user.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户管理
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UserController {

    @Resource
    private UserService userService;

    @GetMapping("/list")
    @ApiOperation(value = "获取所有用户列表")
    public BaseResponse<List<User>> getUserList() {
        return ResultUtils.success(userService.getUserList());
    }

    @GetMapping("/detail")
    @ApiOperation(value = "根据用户id获取用户详情")
    public BaseResponse<User> getUserDetail(Integer uid) {
        return ResultUtils.success(userService.getUserDetail(uid));
    }

    @GetMapping("/detail/with-favorites/{uid}")
    @ApiOperation(value = "获取用户详情（包含收藏信息）")
    public BaseResponse<UserDetailVo> getUserDetailWithFavorites(@PathVariable("uid") Integer uid) {
        return ResultUtils.success(userService.getUserDetailWithFavorites(uid));
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新用户信息")
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest request) {
        return ResultUtils.success(userService.updateUser(request));
    }

    @PostMapping("/cancel")
    @ApiOperation(value = "注销用户")
    public BaseResponse<Boolean> cancel(@RequestBody UserUpdateRequest request) {
        return ResultUtils.success(userService.cancelUser(request));
    }

    @PostMapping("/register")
    @ApiOperation(value = "注册用户")
    public BaseResponse<Boolean> userRegister(@RequestBody User user) {
        if (ObjectUtil.isNull(user) || ObjectUtil.isNull(user.getAccount()) || ObjectUtil.isNull(user.getPwd())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = user.getAccount();
        String userPassword = user.getPwd();
        return ResultUtils.success(userService.userRegister(userAccount, userPassword));
    }

    /**
     * 用户登录
     *
     * @param user
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public BaseResponse<UserVo> userLogin(@RequestBody User user) {
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = user.getAccount();
        String userPassword = user.getPwd();
        return ResultUtils.success(userService.login(userAccount, userPassword));
    }

}
